// <copyright file="HighResolutionTimer.cs" company="Gustavo Franco">
// Copyright (c) 2006 All Right Reserved
// </copyright>
// <author>Gustavo Franco</author>
// <email>gustavo_franco@hotmail.com</email>
// <date>2006</date>
// <summary>Uses native Windows calls to perform high resolution timing.</summary>

using System;
using System.Runtime.InteropServices;

namespace TenneySoftware.Engine.Algorithms.Pathfinder {
    /// <summary>
    /// Uses native Windows calls to perform high resolution timing.
    /// </summary>
    internal static class HighResolutionTimer {
        #region Variables Declaration
        /// <summary>
        /// Counter start time.
        /// </summary>
        private static long startCounter;

        /// <summary>
        /// Machine's timing frequency.
        /// </summary>
        private static long frequency;
        #endregion

        #region Constuctors
        /// <summary>
        /// Initializes static members of the HighResolutionTimer class.
        /// </summary>
        static HighResolutionTimer() {
            QueryPerformanceFrequency(out frequency);
        }
        #endregion

        #region Methods
        /// <summary>
        /// Starts the timer.
        /// </summary>
        public static void Start() {
            QueryPerformanceCounter(out startCounter);
        }

        /// <summary>
        /// Gets the total time that has elapsed.
        /// </summary>
        /// <returns>Returns the elapsed time in seconds.</returns>
        public static double GetTime() {
            long endCounter;
            QueryPerformanceCounter(out endCounter);
            long elapsed = endCounter - startCounter;
            return (double) elapsed / frequency;
        }
        #endregion

        #region Win32APIs
        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Prefer the name given.")]
        private static extern bool QueryPerformanceCounter(out long perfcount);

        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Prefer the name given.")]
        private static extern bool QueryPerformanceFrequency(out long freq);
        #endregion
    }
}

